#include "Mystdio.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include <stdlib.h>
#define FILE_MODE 0666
_FILE* _fopen(const char *filename, const char *flag){
  int fd=-1;
  int f=0;
  if(filename==NULL){
    return NULL;
  }
  if(flag==NULL)
  {
    return NULL;
  }
  if(strcmp(flag,"w")==0){
    f=(O_CREAT|O_WRONLY|O_TRUNC);
    fd = open(filename,f,FILE_MODE);
  }
  
  else if(strcmp(flag,"a")==0){
    f=(O_CREAT|O_WRONLY|O_APPEND);
    fd = open(filename,f,FILE_MODE);
  }
  else if(strcmp(flag,"r")==0){
    f=O_RDONLY;
    fd = open(filename,f);
  }
  else{
    return NULL;
  }
    if(fd==-1){
      return NULL;
    }
    _FILE *fp = (_FILE*)malloc(sizeof(_FILE));
    if(fp==NULL){
      return NULL;
    }
    fp->fileno=fd;
    fp->out_size=0;
    fp->flag=flush_Line;
    return fp;
  
}
int _fwrite(_FILE*fp,const char *s,int len){
  memcpy(&fp->out_buffer[fp->out_size],s,len);
  fp->out_size+=len;
  if(fp->flag&flush_Now){

  write(fp->fileno,fp->out_buffer,fp->out_size);
  fp->out_size=0;  
  }
  else if(fp->flag&flush_Line){
    if(fp->out_buffer[fp->out_size-1]=='\n'){

     write(fp->fileno,fp->out_buffer,fp->out_size);
      fp->out_size=0;
    }
  }
  else if (fp->flag&flush_All){
    if(fp->out_size==SIZE){

  write(fp->fileno,fp->out_buffer,fp->out_size);
       fp->out_size=0;
    }
  }
  return len;
}
void _fflush(_FILE*fp){
  if(fp->out_size>0){
  write(fp->fileno,fp->out_buffer,fp->out_size);
  fp->out_size=0;
  }
}
void _fclose(_FILE*fp){
  if(fp==NULL){
    return;
  }
  _fflush(fp);
  close(fp->fileno);
  free(fp);
}
